﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using EasyStep.Business.Interfaces;
using System.Xml.Serialization;
using System.IO;
using EasyStep.Data.Entities;

namespace EasyStep.Business.Providers
{

    public class FileSystemProviderBase<TEntity> : IDataProvider<TEntity> where TEntity : Entity
    {
        protected List<TEntity> DataList { 
            get 
            {
                if (_DataList == null) 
                {
                    StreamReader reader = new StreamReader(DataStorageFile);
                    _DataList = (List<TEntity>)Serializer.Deserialize(reader);
                    reader.Close();
                }
                return _DataList; 
            }  
        }
        private static List<TEntity> _DataList;
                
        protected XmlSerializer Serializer = new XmlSerializer(typeof(List<TEntity>));
        protected const string DatafileExtension = ".data";
        protected string DataStorageFile { get; set; }
        


        public FileSystemProviderBase(string dataStoragePath) 
        {
            if (string.IsNullOrEmpty(dataStoragePath)) return;
                DataStorageFile = string.Format("{0}\\{1}{2}", dataStoragePath, typeof(TEntity).Name, DatafileExtension);
                if (File.Exists(DataStorageFile))
                {
                    StreamReader reader = new StreamReader(DataStorageFile);
                    _DataList = (List<TEntity>)Serializer.Deserialize(reader);
                    reader.Close();
                }
                else
                {
                    _DataList = new List<TEntity>();
                }
        }
        protected void UpdateData() 
        {
            TextWriter writer = new StreamWriter(DataStorageFile);
            Serializer.Serialize(writer, DataList);
            writer.Close();            
        }

        public IList<TEntity> GetAll()
        {
            return DataList;
        }

        public TEntity Get(Guid id)
        {
            return DataList.Where(e => e.Id.Equals(id)).FirstOrDefault();            
        }

        public TEntity Create(TEntity data)
        {
            DataList.Add(data);
            UpdateData();
            return data;
        }

        public TEntity Update(TEntity data)
        {
            int index = DataList.IndexOf(data);
            if (index != -1)
                DataList[index] = data;
            UpdateData();
            return data;
        }

        public TEntity Delete(TEntity data)
        {
            int index = DataList.IndexOf(data);
            if (index != -1)
                DataList.RemoveAt(index);
            UpdateData();
            return data;
        }
    }
}
